/* 
    ajax的形参采用过了解构对象的形式，其中
    type:表示的是请求方式
    url:表示的目标地址路径
    data:表示的是请求的数据对象
*/


function ajax({type,url,data}) {
    
    return new Promise((resolve, reject) => {
        //获取token
        let token=localStorage.getItem('token');
        //创建XMLHttpRequest对象
        let xhr = new XMLHttpRequest();
        if (type.toUpperCase() == "GET") {
            if (data == undefined) {
                xhr.open(type, url, true);
            } else {
                let newurl = url + "?";
                for (let key in data) {
                    newurl += key + "=" + data[key] + "&";
                }
                newurl = newurl.substring(0, newurl.length - 1);
                xhr.open(type, newurl, true);
            }
            // if(token){
            //     xhr.setRequestHeader("Authorization",token);
            // }else{
            //      //对登录放权
            //     if(url.substring(url.lastIndexOf("/")+1)!="login"){
            //         reject('没有token');
            //     }
               
            // }
            xhr.send(); 
        } else if (type.toUpperCase() == "POST") {
            let params = "";
            for (let key in data) {
                params += key + "=" + data[key] + "&";
            }
            params = params.substring(0, params.length - 1);
            xhr.open(type, url, true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            // if(token){
            //     xhr.setRequestHeader("Authorization",token);
            // }else{
            //     //对登录放权
            //     if(url.substring(url.lastIndexOf("/")+1)!="login"){
            //         reject('没有token');
            //     }
            // }
            xhr.send(params);
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if(xhr.status==200){
                    resolve(xhr.responseText);
                }else if(xhr.status==401){
                    reject("token令牌过期");
                }
            }
        }
    })
}

//上传文件的ajax方法
function ajaxUploadFile(url,files,token){
    return new Promise((resolve,reject)=>{
        let xhr=new XMLHttpRequest();
        xhr.open("POST",url,true);
        //上传文件通过FormData
        let formData=new FormData();
        formData.append("file",files[0]);
        if(token){
            xhr.setRequestHeader("Authorization",token);
        }
        xhr.send(formData);
        xhr.onreadystatechange=function(){
            if(xhr.readyState==4){
                if(xhr.status==200){
                    resolve(xhr.responseText);
                }
            }
        }
    })
}
